package com.witsight.platform.util.lang;

import java.beans.PropertyDescriptor;
import java.util.List;

import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.witsight.platform.model.BoEntity;
import com.witsight.platform.model.IBaseObject;

/**   
 * 说明：实体工具类
 * @Title: BeanUtil.java 
 * @Package com.witsight.platform.util.lang 
 * @See: {@link BeanUtils}
 * Copyright: Copyright (c) 2017
 * Company:sany huax witsight team by product
 * @author: penght  
 * @date: 2017年9月21日 下午2:45:32 
 * @version: V1.0
 *
 */
public abstract class BeanUtil extends BeanUtils {
	/**
	 * 说明：定义后能再同一类中使用static常量log
	 */
	private static final Logger log = LoggerFactory.getLogger(BeanUtil.class);
	private static final List<String> model_filters =CollectionUtil.arrayToList("class", "sreach", "isNew");
	/**
	 * 
	 * 说明：将实体转化为Map对象可以随意取得对应的属性
	 * @Title: getBeanMap
	 * @See: {@link #getBeanMap(Object)}
	 * @author penght
	 * @param object 实体
	 * @return Map对象
	 * @date: 2017年9月21日 下午2:52:42
	 */
	public static BeanMap getBeanMap(Object object) {
		BeanMap beanMap = new BeanMap(object);
		return beanMap;
	}
	/**
	 * 
	 * 说明：对象转换Map 
	 * 需要继承IBaseObject的对象bean 才可以转换，对象属性是IBaseObject的时候也会转换属性
	 * 
	 * @Title: object2Maps
	 * @See: {@link #object2Maps(IBaseObject)}
	 * @author penght
	 * @param bean IBaseObject的对象bean
	 * @return BoEntity
	 * @date: 2017年10月9日 下午2:07:31
	 */
	public static BoEntity object2Maps(IBaseObject bean) {
		if (bean == null) {
			return (new BoEntity());
		}
		
		if (bean instanceof BoEntity) {
			return (BoEntity) bean;
		}
		if (log.isDebugEnabled()) {
			log.debug("Describing bean: " + bean.getClass().getName());
		}
		BoEntity result = new BoEntity();
		PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
		parseBean(result, propertyUtilsBean, bean);
		return result;
	}
	/**
	 * 
	 * 说明：将IBaseObject
	 * @Title: parseBean
	 * @author penght 
	 * @param result
	 * @param propertyUtilsBean
	 * @param baseObject
	 * @param parent 
	 * @date: Jul 2, 2017 11:56:03 AM
	 */
	private static void parseBean(BoEntity result, PropertyUtilsBean propertyUtilsBean,
			IBaseObject baseObject) {
		if (baseObject == null) {
			return;
		}
		PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(baseObject);
		for (PropertyDescriptor descriptor :  descriptors) {
			String name = descriptor.getName();
			if (model_filters.contains(name)) {
				continue;
			}
			if (propertyUtilsBean.getReadMethod(descriptor) != null) {
				try {
					Object obj = propertyUtilsBean.getNestedProperty(baseObject, name);
					if (obj == null) {
						continue;
					}
					if (obj instanceof IBaseObject) {						
						parseBean(result, propertyUtilsBean , (IBaseObject) obj);
					}
					result.put(name, obj);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
